import com.googlecode.linkmein.domain.Employee
import com.googlecode.linkmein.domain.Employees
import com.googlecode.linkmein.domain.Project
import com.googlecode.linkmein.repository.ObjectStorage
import com.googlecode.linkmein.service.DateFormatter
import com.googlecode.linkmein.service.FetchEmployeeService

class ProjectsController {
    FetchEmployeeService fetchEmployeeService
    ObjectStorage storage

    def beforeInterceptor = {
        if (!session.getAttribute("gmail")){
            flash["error"] = "Please login with your google account and make sure your google account is in our list."
            redirect(uri: "/error.gsp")
            return false
        }
    }
    
    def show = {
        Map peopleByProjects = fetchEmployeeService.getProjects().orderedByProjects()
        Project project = new Project(params.name)

        if (peopleByProjects.keySet().contains(project)) {
            def change = storage.findNewProjectChangeByName(params.name)

            Employees people = peopleByProjects[project]
            def projects = new ArrayList(peopleByProjects.keySet())
            Map model = [project: project,
                    prevProject: getPrevProject(projects, project),
                    nextProject: getNextProject(projects, project),
                    peopleByRoles: getPeopleByRole(people)]
            if (change != null) {
                model["creationTime"] = DateFormatter.format(change.createdAt)
            }
            render(view: "show", model: model)
        }
        else {
            flash["error"] = "The project you are requesting does not exist"
            redirect(uri: "/error.gsp")
        }
    }

    private def getPrevProject(projects, project) {
        return projects[(projects.indexOf(project) - 1 + projects.size()) % projects.size()];
    }

    private def getNextProject(projects, project) {
        return projects[(projects.indexOf(project) + 1) % projects.size()];
    }

    private def getPeopleByRole(Employees people) {
        Map peopleByRoles = [:];
        for (Employee e: people) {
            if (peopleByRoles.containsKey(e.role)) {
                peopleByRoles[e.role].add(e);
            }
            else {
                peopleByRoles[e.role] = [e];
            }
        }
        return peopleByRoles;
    }
}
